<template>
  <div class="container">
    <el-form :inline="true" :model="filterData" class="search">
      <el-form-item label="">
        <el-input
          style="width: 250px"
          clearable
          placeholder="名称"
          v-model="filterData.importFileName"
        />
      </el-form-item>
      <el-form-item>
        <el-button :icon="Search" @click="search" />
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="dialog.isOpen = true"
          >导入</el-button
        >
        <el-button
          type="primary"
          style="margin-left: 10px"
          @click="getTemplateDownload"
          >下载模版</el-button
        >
      </el-form-item>
    </el-form>
    <div class="table-contain">
      <Table
        height="100%"
        :columns="tableDataColumns"
        v-loading="loading"
        :data="tableData"
        @row-click="rowClick"
      >
        <template #edit="{ row }">
          <el-button
            size="small"
            :icon="Edit"
            plain
            type="success"
            @click="addD(row, true, 1)"
          >
            加入
          </el-button>
          <el-button
            size="small"
            :icon="Edit"
            plain
            type="warning"
            @click="addD(row, false, 2)"
          >
            移除
          </el-button>
          <el-button
            size="small"
            :icon="Delete"
            plain
            type="danger"
            @click="del(row)"
          >
            删除
          </el-button>
        </template>
      </Table>
    </div>
    <el-dialog
      v-model="dialog.isOpen"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        :label-width="100"
        :model="formData"
        ref="ruleFormData"
        :rules="rules"
      >
        <el-form-item label="题库类型：" prop="questionTypeId">
          <el-select
            v-model="formData.questionTypeId"
            placeholder=""
            style="width: 100%"
          >
            <el-option
              v-for="item in typeList"
              :key="item.id"
              :label="item.questionTypeName"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="导入题库：">
          <el-upload
            ref="uploadRef"
            class="upload-demo"
            :auto-upload="false"
            :on-change="obChange"
            :before-remove="beforeRemove"
            :headers="{ [`x-auth-token`]: xAuthToken }"
            :action="`${baseURL}/manage/v1/questionImport/read?dir=file&&questionTypeId=${formData.questionTypeId}`"
            :on-success="onUploadSuccess"
          >
            <template #trigger>
              <el-button type="primary">上传</el-button>
            </template>
          </el-upload>
        </el-form-item>
        <div
          style="border: 1px solid #eee; padding: 0 10px; border-radius: 10px"
        >
          <p>导入规则：</p>
          <p>
            1、题目类型使用”标题2“样式。单选题有“单选题”字样，多选题有”多选题“字样，判断题有“判断题”字样；
          </p>
          <p>2、题目需要使用“标题3”样式，需要使用自动排序即可；</p>
          <p>3、题目选项需要使用自动排序方式（判断题除外）；</p>
          <p>4、答案需要使用冒号(支持中英文)隔开；</p>
          <p>5、判断题只需填写答案即可，无需列出选项；</p>
          <p>6、校验题目是否重复，截取题目所有文本作为题目唯一性标识；</p>
          <p>7、导入重复的题目会跳过</p>
        </div>
      </el-form>
      <div class="footer">
        <el-button
          type="primary"
          :loading="submitLoading"
          @click="submitUpload(ruleFormData)"
        >
          保存
        </el-button>
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </el-dialog>
    <Page
      :page-data="pageData"
      :total="total"
      @page-no-change="pageNoChange"
      @page-size-change="pageSizeChange"
    />
    <DictEditForm
      v-model:visible="editFormVisible"
      v-model:data="rowData"
      type="1"
      @submit="getTableData"
    />
  </div>
</template>

<script lang="ts" setup>
import { onMounted, ref, watch, reactive } from "vue";
import Page from "@/components/pageTable/Page.vue";
import Table from "@/components/pageTable/table";
import { ElMessage, ElMessageBox, FormInstance, FormRules } from "element-plus";
import { Delete, Edit, Search } from "@element-plus/icons-vue";
import DictEditForm from "@/views/systemManage/dictionary/components/DictEditForm.vue";
import { bus } from "@/util";
import { usePage } from "@/hooks/usePage.ts";
import {
  addQuestion,
  delQuestionImport,
  pageQuestionImport,
} from "@/api/databaseManage.ts";
import { selectQuestionTypes } from "@/api/system.ts";
import { baseURL } from "@/util/request";

let rowData: any;
const editFormVisible = ref<boolean>(false);
let filterData = ref({ importFileName: "" });
const xAuthToken = ref<string>(localStorage.getItem("x-auth-token"));
const uploadRef = ref();
const uploadFileList = ref<[]>([]);
const typeList = ref<[]>([]);
const submitLoading = ref<boolean>(false);
const ruleFormData = ref();

//TODO 做成动态
const rules = reactive<FormRules<IForm>>({
  questionTypeId: [{ required: true, message: "请选择", trigger: "change" }],
});

interface IForm {
  id: string;
  questionTypeId: string;
}
const formData = reactive<IForm>({
  id: "",
  questionTypeId: "",
});

const tableDataColumns = [
  { prop: "importFileName", label: "名称", width: 230 },
  { prop: "questionTypeName", label: "题库类型", width: 110 },
  { prop: "questionTotal", label: "题目", width: 70 },
  { prop: "relaQuestionTotal", label: "导入", width: 70 },
  { prop: "addQuestionTotal", label: "入库", width: 70 },
  { prop: "edit", label: "操作", width: 250, template: true },
];
let dialog = reactive({
  isOpen: false,
  title: "",
});
const {
  loading,
  tableData,
  pageData,
  total,
  search,
  pageNoChange,
  pageSizeChange,
} = usePage(pageQuestionImport, filterData);

function rowClick(row: any) {
  bus.emit("searchValue", row?.id);
}

async function getTableData() {
  await search();
  bus.emit("searchDictValue", null);
}

async function getTypeList() {
  const { data, msg, success } = await selectQuestionTypes({
    isComprehensive: true,
  });
  if (!success) {
    ElMessage.error(msg);
    return;
  }
  typeList.value = data;
}

async function getTemplateDownload() {
  const link = document.createElement("a");
  link.href = baseURL + "/image/show/temp/消防安全平台考试模板.docx";
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
}

async function addD(row: any, sign: boolean, type: number) {
  if (type === 2) {
    ElMessageBox.confirm(
      `是否移除已入库的 ${row.addQuestionTotal} 道题?`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      },
    ).then(async () => {
      addQuestionFn(row.id, sign);
    });
  } else {
    addQuestionFn(row.id, sign);
  }
}

async function addQuestionFn(id: any, sign: any) {
  const { success } = await addQuestion({ id, isAdd: sign });
  if (!success) {
    return;
  }
  ElMessage.success("操作成功");
  bus.emit("searchValue", id);
  await search();
}

async function del(row: any) {
  ElMessageBox.confirm(`是否删除?`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    const { success, msg } = await delQuestionImport({ id: row?.id });
    if (!success) {
      ElMessage.error(msg);
      return;
    }
    ElMessage.success("操作成功");
    await getTableData();
  });
}

function clearUploadFile() {
  uploadRef.value?.clearFiles();
}

function closeDialog() {
  if (uploadRef.value) {
    uploadRef.value.clearFiles();
  }
  resetForm(ruleFormData.value);
  submitLoading.value = false;
  formData.questionTypeId = "";
  dialog.isOpen = false;
}
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

function obChange(file: any, fileList: []) {
  uploadFileList.value = fileList;
}
function beforeRemove(file: any, fileListVal: []) {
  uploadFileList.value = fileListVal;
}

function onUploadSuccess(response: any) {
  if (response?.code === 500) {
    ElMessage.error(response?.msg || "上传错误！");
    clearUploadFile();
    submitLoading.value = false;
    return;
  }
  //formData.videoFileUrl = response?.data?.fileUrl;
  search();
  dialog.isOpen = false;
  submitLoading.value = false;
  ElMessage.success("上传完成！");
}

const submitUpload = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid, fields) => {
    if (valid) {
      if (uploadFileList.value <= 0) {
        ElMessage.success("请上传题库文件！");
        return;
      }
      submitLoading.value = true;
      uploadRef.value!.submit();
    } else {
      console.log("error submit!", fields);
    }
  });
};
watch(filterData.value, async () => {
  await getTypeList();
  bus.emit("searchValue", "");
});
watch(dialog, async () => {
  await getTypeList();
});
onMounted(async () => {
  await getTableData();
});
</script>

<style scoped lang="scss">
@import "@/assets/styles/common";
.upload-demo{
  width: 100%;
}
.footer {
  width: 100%;
  text-align: center;
  margin-top: 10px;
}
</style>
